﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;

namespace RRSClientWebApp
{
    //Includes utility classes to read the endpoint and get the list of web service
    //parameters that need to be passed in with the request.
    //The parameters are used in the default.aspx page to generate the input controls.
    public class Util
    {
        //Retruns a comma separated list of columns which are parameters 
        //that need to be passed in to the endpoint .
        public string getColumnsListFromAPIUrl(string restEndpointUrl)
        {
            //get oData from REST
            string odataUrl = convertRestToOdata(restEndpointUrl);

            //get columns list using oData
            string columns = getColumnListUsingOData(odataUrl);

            return columns;
        }
        //Convert the endpoit url to odata to use it to get input field list
        private string convertRestToOdata(string uri1)
        {
            string[] del = { "/" };
            string[] primeurl = uri1.Split(del, StringSplitOptions.RemoveEmptyEntries);
            string odataurl = primeurl[0] + "//" + primeurl[1] + "/odata/" + primeurl[2] + "/" + primeurl[3] + "/" + primeurl[4] + "/" + primeurl[5] + "/$metadata";

            return odataurl;
        }
        //Call the service to get the list of columns (input fields)
        private string getColumnListUsingOData(string odata)
        {
            string columnList = "";
            WebRequest request;
            Stream result;
            try
            {
                request = WebRequest.Create(odata);
                request.Method = "GET";
                request.ContentType = "application/json; charset=utf-8";
                WebResponse res = request.GetResponse();
                result = res.GetResponseStream();
            }
            catch (Exception e1)
            {
                return "Failed to connect to REST API endpoint: " + e1.Message + ". Please check the URL";
                // return;
            }

            bool firstColumn = true;
            using (StreamReader sr = new StreamReader(result))
            {
                string newline;

                while ((newline = sr.ReadLine()) != null)
                {
                    string[] parm;
                    string[] paramDelimiter = { "Parameter Name=" };
                    string[] removeTrailingDelimiter = { " Type" };
                    parm = newline.Split(paramDelimiter, StringSplitOptions.RemoveEmptyEntries);
                    if (parm.Length > 1)
                    {
                        string colName = (parm[1].Split(removeTrailingDelimiter, StringSplitOptions.RemoveEmptyEntries))[0];
                        colName = RemoveSpecialCharacters(colName);
                        if (firstColumn)
                        {
                            columnList += colName;
                            firstColumn = false;
                        }
                        else
                            columnList += "," + colName;
                    }
                }

            }
            return columnList;
        }
        //Removes special characters from input fields returned by the service
        public static string RemoveSpecialCharacters(string input)
        {
            Regex r = new Regex("(?:[^a-z0-9-]|(?<=['\"]))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
            return r.Replace(input, String.Empty);
        }
    }
}